<template>
	<view style="width: 100%;height: 100%;">
		<view id="mapDiv" class="mapDiv" :apikey="apiKey" :prop="option" :change:prop="Trenderjs.initTMap"></view>
	</view>
</template>

<script>
	export default {
		name: 'TianDiTu-Map',
		data() {
			return {
				Tmap: null,
				option: {
					type: '',
					apikey: '',
					lng: '',
					lat: '',
					list: []
				},
			}
		},
		props: {
			apiKey: {
				type: String,
				require: true,
				default: ''
			},
			customIcon: {
				type: String,
				default: ''
			}
		},
		methods: {
			initCharts(lng, lat, list, pd) {
				this.option = {
					apikey: this.apiKey,
					lng,
					lat,
					type: 'open',
					list: list,
					pand: pd
				}
			},
			async bjd(e) {
				this.$emit('onSelect', e)
			}
		}
	}
</script>

<script module="Trenderjs" lang="renderjs">
	var Tmap = null;
	export default {
		data() {
			return {
				options: {},
			}
		},
		mounted() {},
		methods: {
			initTMap(newValue, oldValue, ownerInstance, instance) {
				this.options = newValue
				if (newValue.type === 'open' && newValue.apikey) {
					if (newValue.pand) {
						const script = document.createElement('script')
						script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=' + this.options.apikey
						script.onload = this.initChartsRender.bind(this)
						document.head.appendChild(script)
					} else {
						const {
							lng,
							lat
						} = this.options
						// Tmap.removeOverLay()
						let newMarker = Tmap.getOverlays(); // 获取到了地图上的所有点
						newMarker.forEach((item) => {
							Tmap.removeOverLay(item);
						});
						Tmap.centerAndZoom(new T.LngLat(lng, lat), 12);
						this.setIcon()
					}
				}
			},
			initChartsRender() {
				const {
					lng,
					lat
				} = this.options
				var that = this;
				Tmap = new T.Map('mapDiv', {
					projection: 'EPSG:4326',
				});
				Tmap.disableDoubleClickZoom()
				Tmap.centerAndZoom(new T.LngLat(lng, lat), 12);
				this.setIcon()
			},
			setIcon() {
				var wz = this.options.list
				let initMarker = []; //存放节点
				//data 这里是多个节点坐标、及文字标注
				wz.length && wz.forEach((item) => {
					const marker = new T.Marker(new T.LngLat(item.lon, item.lat), {
						icon: new T.Icon({
							iconUrl: item.iconPath,
							iconSize: new T.Point(item.width,item.height)
						}),
					});
					const handleClick = () => {
					  this.$ownerInstance.callMethod('bjd', item.id)
					}
					marker.addEventListener('click', handleClick);
					initMarker.push(marker);
				});
				initMarker.forEach((item) => {
					Tmap.addOverLay(item);
				});
			},
		},
	}
</script>

<style scoped>
	#mapDiv {
		width: 100%;
		height: 100%;
	}

	/* /deep/ .tdt-control-copyright {
		display: none;
	} */
	
</style>